<script lang="ts" setup>
import { reactive, ref, onMounted, inject,onUnmounted  } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'; // 引入 useRouter
import CryptoJS from 'crypto-js';
import { ElMessage } from 'element-plus'; // 引入 ElMessage
const axios = inject('axios') //注入 axios
// References
const ruleFormRef = ref<FormInstance>()
// 创建路由对象，用于编程式导航
const router = useRouter()

const ruleForm = reactive({
    newpass: '', // 新密码
    checkPass: '', // 确认密码
    email: '', // 邮箱
    emailCode: '', // 验证码
})

//通过后台接口获取用户信息
//解密token
function getToken() {
    const encryptedToken = localStorage.getItem('token');
    if (encryptedToken) {
        const secretKey = 'your_secret_key'; // 使用相同的密钥
        const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
        const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
        return decryptedToken;
    }
    return null;
}
//获取用户信息
function initUser() {
    //判断用户是否登录
    //判断用户是否登录
    const Token = getToken();
    if (Token != '') {
        axios({
            method: 'get',
            url: 'http://localhost:8080/user/getuser',
            headers: {
                Authorization: 'Bearer ' + Token
            }
        })
            .then(function (response) {
                if (response.data.code == '200') {
                    //将获取到的邮箱填入表单
                    ruleForm.email = response.data.user.email
                    console.log("用户邮箱获取成功：" + response.data.user.email)

                    // ruleForm.email = user.value.email
                }
            })
            .catch(function (error) {
                console.log("获取用户信息失败" + error.response.status)
                console.log(error)
                if (error.response.status == 401) { 
                        token.value = ''
                        userStore.setToken('')
                    //提示
                    ElMessage({
                        message: '请重新登录',
                        type: 'error',
                        plain: true
                    })
                    console.log("重新登录")
                    router.push('/login')
                }
            })
    }
}

const rules: FormRules = {
    newpass: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 8, message: '密码长度不能少于8个字符', trigger: 'blur' },
        { max: 12, message: '密码长度不能超过12个字符', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                const regex = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,12}$/;
                if (!value) {
                    callback(new Error('请输入新密码'));
                } else if (!regex.test(value)) {
                    callback(new Error('密码必须包含字母、数字和特殊字符'));
                } else {
                    callback(); // 验证通过
                }
            },
            trigger: 'blur'
        }
    ],
    checkPass: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请确认新密码'));
                } else if (value !== ruleForm.newpass) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback(); // 验证通过
                }
            }, trigger: 'blur'
        }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
    ],
    emailCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        {
            min: 6, message: '验证码长度必须为6个字符', trigger: 'blur'
        },
        {
            max: 6, message: '验证码长度必须为6个字符', trigger: 'blur'
        }
    ]
}



// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 发送验证码的状态
const isCounting = ref(false);
const countdown = ref(60); // 倒计时的秒数
let countdownInterval: ReturnType<typeof setInterval> | null = null;
// 发送验证码的函数
const sendCode = async () => {
    // if (!ruleForm.email) {
    //     alert('请联系管理员处理！'); // 确保输入邮箱
    //     return;
    // }
    console.log("发送验证码")
    console.log(ruleForm.email)
    // TODO: 发送验证码的逻辑
    try {
        const response = await axios.get(`http://localhost:8080/user/forgetpassCode/${ruleForm.email}`);
        console.log(response);
        console.log(response.data.code);
        if (response.data.code === 200) {
            // 启动倒计时
            isCounting.value = true;
            countdown.value = 60; // 重置倒计时
            countdownInterval = setInterval(() => {
                countdown.value--;
                if (countdown.value <= 0) {
                    clearInterval(countdownInterval!);
                    isCounting.value = false; // 重置计时状态
                }
            }, 1000);
            ElMessage({
                message: '验证码已发送！',
                type: 'success',
                plain: true
            });
        }
        else {
            ElMessage({
                message: '验证码发送失败，错误代码：' + response.data.code,
                type: 'error',
                plain: true
            });
        }
    } catch (error) {
        ElMessage({
            message: '验证码发送失败！',
            type: 'error',
            plain: true
        });
        console.error(error); // 提供更多的错误调试信息
    }
}
// 提交表单的函数
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    const Token = getToken();
    formEl.validate((valid) => {
        if (valid) {
            try{
                console.log("提交表单")
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/user/forgetpassword',
                    data: {
                        email: ruleForm.email,
                        emailcode: ruleForm.emailCode,
                        newPassword: ruleForm.newpass
                    },
                    headers: {
                        Authorization: 'Bearer ' +Token
                    }
                })
                .then(response => {
                    console.log(response)
                    if (response.data.code === 200) {
                        ElMessage({
                            message: response.data.message,
                            type: 'success',
                            plain: true
                        });
                        router.push('/login')
                    }
                    else {
                        ElMessage({
                            message: '密码修改失败，错误代码：' + response.data.code,
                        })
                    }
                })
            }catch(error){
                console.error("出现错误："+error);
            }
        } else {
            console.log('表单验证失败');
          
        }
    });
}
// 完成初始渲染并创建 DOM 节点后，进行页面加载
onMounted(() => {
    //初始化数据
    initUser()
})
// 在组件卸载时清除计时器
onUnmounted(() => {
    if(countdownInterval !== null){
        clearInterval(countdownInterval);
    }
    
});
</script>

<template>
    <div class="container">
        <el-form ref="ruleFormRef" style="max-width: 600px; width: 100%" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <h1 class="form-title">密码找回</h1>
            <!-- <el-form-item label="请输入旧密码" prop="oldPass">
                <el-input v-model="ruleForm.oldPass" type="password" autocomplete="off" />
            </el-form-item> -->
            <el-form-item label="请输入新密码" prop="newpass">
                <el-input v-model="ruleForm.newpass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="请重新输入新密码" prop="checkPass">
                <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="请输入邮箱" prop="email" class="email-input-wrapper">
                <el-input v-model="ruleForm.email" class="email-input" disabled />
                <el-button :disabled="isCounting" type="primary" @click="sendCode" style="width: 80px;">
                    {{ isCounting ? `${countdown}秒后重发` : '发送验证码' }}
                </el-button>
            </el-form-item>
            <el-form-item label="请输入验证码" prop="emailCode">
                <el-input v-model="ruleForm.emailCode" />
            </el-form-item>

            <el-divider content-position="center"></el-divider>
            <el-form-item class="button-container" style="text-align: center;">
                <div style="display: inline-flex; gap: 10px;"> <!-- 使用 inline-flex 添加间距 -->
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped lang="scss">
.container {

    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    /* 背景模糊效果 */
    background: rgba(255, 255, 255, 0.5);
    /* 半透明背景 */
    backdrop-filter: blur(15px);
    /* 模糊背景 */
}

.form-title {
    text-align: center;
    /* 标题居中 */
    width: 100%;
    /* 使标题占据 100% 宽度 */
}

.button-container {
    text-align: center;
    /* 按钮块居中 */
    margin-top: 20px;
    /* 可选：添加按钮的上方间距 */
}

.email-input-wrapper {
    display: flex;
    align-items: center;
    /* 垂直居中对齐 */
}

.email-input {
    flex: 1;
    /* 输入框占据剩余空间 */
    margin-right: 10px;
    /* 输入框与按钮之间的间距 */
}
</style>